/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.view;

import canteen.sys.model.entity.ItemMaster;
import canteen.sys.model.entity.ItemTypeMaster;
import canteen.sys.model.generic.HibernateDAOFactory;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author TNT
 */
public class ItemEntry extends javax.swing.JInternalFrame implements ActionView<ItemMaster> {

    HibernateDAOFactory hibernateDAOFactory = HibernateDAOFactory.getInstance();
    DefaultTableModel modelTable;

    /**
     * Creates new form ItemEntry
     */
    public ItemEntry() {
        initComponents();
        modelTable = (DefaultTableModel) tableItem.getModel();
        getListItemType();
        List<ItemMaster> listItem = hibernateDAOFactory.getItemMasterDAO().findAll();
        showList(listItem);
        listSelectionListener();
        listenerTableModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btsave = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        btcancel = new javax.swing.JButton();
        txtDepID = new javax.swing.JTextField();
        txtDepName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        rbStatus = new javax.swing.JRadioButton();
        cbItemType = new javax.swing.JComboBox();
        txtItemRate = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtqty = new javax.swing.JTextField();
        jLayeredPane2 = new javax.swing.JLayeredPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableItem = new javax.swing.JTable();

        setClosable(true);
        setTitle("Item Entry");

        jLayeredPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Box"));
        jLayeredPane1.setToolTipText("");

        jLabel1.setText("Item ID");
        jLabel1.setBounds(10, 30, 130, 14);
        jLayeredPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setText("Item Name");
        jLabel2.setBounds(10, 70, 130, 14);
        jLayeredPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btsave.setText("Save");
        btsave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btsaveActionPerformed(evt);
            }
        });
        btsave.setBounds(10, 270, 80, 23);
        jLayeredPane1.add(btsave, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btdelete.setText("Delete");
        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btdeleteActionPerformed(evt);
            }
        });
        btdelete.setBounds(110, 270, 80, 23);
        jLayeredPane1.add(btdelete, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btcancel.setText("Cancel");
        btcancel.setEnabled(false);
        btcancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btcancelActionPerformed(evt);
            }
        });
        btcancel.setBounds(210, 270, 80, 23);
        jLayeredPane1.add(btcancel, javax.swing.JLayeredPane.DEFAULT_LAYER);

        txtDepID.setEnabled(false);
        txtDepID.setBounds(150, 30, 190, 20);
        jLayeredPane1.add(txtDepID, javax.swing.JLayeredPane.DEFAULT_LAYER);
        txtDepName.setBounds(150, 70, 190, 20);
        jLayeredPane1.add(txtDepName, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setText("Status");
        jLabel3.setBounds(10, 230, 90, 14);
        jLayeredPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        rbStatus.setSelected(true);
        rbStatus.setBounds(150, 230, 21, 21);
        jLayeredPane1.add(rbStatus, javax.swing.JLayeredPane.DEFAULT_LAYER);

        cbItemType.setBounds(150, 110, 190, 20);
        jLayeredPane1.add(cbItemType, javax.swing.JLayeredPane.DEFAULT_LAYER);
        txtItemRate.setBounds(150, 150, 190, 20);
        jLayeredPane1.add(txtItemRate, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel4.setText("Item Type Name");
        jLabel4.setBounds(10, 110, 120, 14);
        jLayeredPane1.add(jLabel4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel5.setText("Item Rate");
        jLabel5.setBounds(10, 150, 100, 14);
        jLayeredPane1.add(jLabel5, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel6.setText("$");
        jLabel6.setBounds(134, 150, 10, 20);
        jLayeredPane1.add(jLabel6, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel7.setText("Quantity");
        jLabel7.setBounds(10, 190, 80, 14);
        jLayeredPane1.add(jLabel7, javax.swing.JLayeredPane.DEFAULT_LAYER);
        txtqty.setBounds(150, 190, 190, 20);
        jLayeredPane1.add(txtqty, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLayeredPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Click on Record to Delete or Edit"));

        tableItem.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Item Name", "Item Type Name", "Rate", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableItem);
        tableItem.getColumnModel().getColumn(0).setMaxWidth(50);
        tableItem.getColumnModel().getColumn(3).setResizable(false);
        tableItem.getColumnModel().getColumn(4).setMaxWidth(100);

        jScrollPane1.setBounds(10, 20, 450, 370);
        jLayeredPane2.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 359, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLayeredPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLayeredPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 302, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btsaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btsaveActionPerformed
        // TODO add your handling code here:
        try {
            ItemMaster itemMaster = new ItemMaster();
            if (btsave.getText().equals("Save")) {
                itemMaster.setItemName(txtDepName.getText());
                itemMaster.setItemRate(Double.parseDouble(txtItemRate.getText()));
                itemMaster.setStatus(rbStatus.isSelected());
                ComboboxRecInfo<ItemTypeMaster> combobox = (ComboboxRecInfo<ItemTypeMaster>) cbItemType.getSelectedItem();
                if (!txtqty.getText().equals("") || txtqty.getText() != null) {
                    itemMaster.setItemType(combobox.getKeyData());
                } else {
                    JOptionPane.showMessageDialog(this, "Quantity must input!");
                }
                itemMaster.setQuantity(Integer.parseInt(txtqty.getText()));
                validSaveOrUpdateItemType(itemMaster);
            } else {
                itemMaster.setItemId(Integer.parseInt(txtDepID.getText()));
                itemMaster.setItemName(txtDepName.getText());
                itemMaster.setItemRate(Double.parseDouble(txtItemRate.getText()));
                itemMaster.setStatus(rbStatus.isSelected());
                ComboboxRecInfo<ItemTypeMaster> combobox = (ComboboxRecInfo<ItemTypeMaster>) cbItemType.getSelectedItem();
                itemMaster.setItemType(combobox.getKeyData());
                itemMaster.setQuantity(Integer.parseInt(txtqty.getText()));
                validSaveOrUpdateItemType(itemMaster);
            }
            this.txtDepName.requestFocus();
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(this, "Add new Item Fail!\n Error: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Item Rate or Quantity fomat error!\n Error: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
            this.txtItemRate.requestFocus();
        }
    }//GEN-LAST:event_btsaveActionPerformed

    private void btdeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btdeleteActionPerformed
        // TODO add your handling code here:
        int indexRow = tableItem.getSelectedRow();
        if (indexRow != -1) {
            try {
                if (modelTable.getRowCount() > 1) {
                    hibernateDAOFactory.getItemMasterDAO().makeTransient(getObject(indexRow));
                    deleteRow(indexRow);
                }
            } catch (HibernateException ex) {
                JOptionPane.showMessageDialog(this, "Can't delete Item \nError: " + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(this, "No row selected!", "Warning", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btdeleteActionPerformed

    private void btcancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btcancelActionPerformed
        // TODO add your handling code here:
        //        DepartmentMaster departmentMaster = new DepartmentMaster();
        //        departmentMaster.setDepartmentName("TNTuyen");
        //        departmentMaster.setStatus(false);
        //        updateRow(departmentMaster, 2);
        //this.dispose();
    }//GEN-LAST:event_btcancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btcancel;
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btsave;
    private javax.swing.JComboBox cbItemType;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLayeredPane jLayeredPane2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbStatus;
    private javax.swing.JTable tableItem;
    private javax.swing.JTextField txtDepID;
    private javax.swing.JTextField txtDepName;
    private javax.swing.JTextField txtItemRate;
    private javax.swing.JTextField txtqty;
    // End of variables declaration//GEN-END:variables

    @Override
    public void deleteRow(int index) {
        if (modelTable.getRowCount() > 0) {
            if (index > 0) {
                tableItem.setRowSelectionInterval(index - 1, index - 1);
                modelTable.removeRow(index);
            } else {
                tableItem.setRowSelectionInterval(index + 1, index + 1);
                modelTable.removeRow(0);
            }
        } else {
            JOptionPane.showMessageDialog(this, "There is no row to delete!", "Warning!", JOptionPane.WARNING_MESSAGE);
        }
    }

    @Override
    public void updateRow(ItemMaster row, int index) {
        tableItem.setValueAt(row.getItemId(), index, 0);
        tableItem.setValueAt(row.getItemName(), index, 1);
        tableItem.setValueAt(row.getItemType().getItemTypeName(), index, 2);
        tableItem.setValueAt("$" + row.getItemRate(), index, 3);
        String status = "disable";
        if (row.isStatus()) {
            status = "enable";
        }
        tableItem.setValueAt(status, index, 4);
    }

    @Override
    public void addRow(ItemMaster row, boolean posion) {
        String status = "disable";
        if (row.isStatus()) {
            status = "enable";
        }
        if (posion) {
            modelTable.insertRow(0, new Object[]{row.getItemId() + "",
                        row.getItemName(),
                        row.getItemType().getItemTypeName(),
                        "$" + row.getItemRate(),
                        status});
        } else {
            modelTable.insertRow(tableItem.getRowCount(), new Object[]{row.getItemId() + "",
                        row.getItemName(),
                        row.getItemType().getItemTypeName(),
                        "$" + row.getItemRate(),
                        status});
        }
    }

    @Override
    public final void showList(List<ItemMaster> list) {
        String status;
        for (int i = 0; i < 4; i++) {
            modelTable.removeRow(0);
        }
        for (ItemMaster item : list) {
            if (item.isStatus()) {
                status = "enable";
            } else {
                status = "disable";
            }
            modelTable.insertRow(0, new Object[]{item.getItemId() + "",
                        item.getItemName(),
                        item.getItemType().getItemTypeName(),
                        "$" + item.getItemRate(),
                        status});
        }
    }

    @Override
    public void showDetail(ItemMaster object) {
        txtDepID.setText(object.getItemId() + "");
        txtDepName.setText(object.getItemName());
        cbItemType.setSelectedItem(object.getItemType().getItemTypeName());
        txtItemRate.setText(object.getItemRate() + "");
        rbStatus.setSelected(object.isStatus());
    }

    @Override
    public ItemMaster getObject(int index) {
        ItemMaster itemMaster = new ItemMaster();
        boolean status = false;
        itemMaster.setItemId(Integer.parseInt(modelTable.getValueAt(index, 0).toString()));
        itemMaster.setItemName(modelTable.getValueAt(index, 1).toString());
        int indexCb = ComboboxRecInfo.findCbKeyDataIndex(cbItemType, modelTable.getValueAt(index, 2).toString(), 0);
        double itemRate = Double.parseDouble(modelTable.getValueAt(index, 3).toString().substring(1));
        itemMaster.setItemRate(itemRate);
        ComboboxRecInfo<ItemTypeMaster> cbRecInfo = (ComboboxRecInfo) cbItemType.getItemAt(indexCb);
        ItemTypeMaster itemTypeMaster = cbRecInfo.getKeyData();
        itemMaster.setItemType(itemTypeMaster);
        if (modelTable.getValueAt(index, 4).equals("enable")) {
            status = true;
        }
        itemMaster.setStatus(status);
        return itemMaster;
    }

    @Override
    public boolean validObject(ItemMaster object) {
        if (object.getItemName().equals("") || object.getItemName() == null) {
            JOptionPane.showMessageDialog(this, "Item Name must input!");
            return false;
        } else if (object.getItemRate() < 0) {
            JOptionPane.showMessageDialog(this, "Item Rate must > 0 !");
            return false;
        } else if (object.getQuantity() < 0) {
            JOptionPane.showMessageDialog(this, "Item Quantity must > 0 !");
            return false;
        }
        return true;
    }

    public final void getListItemType() {
        List<ItemTypeMaster> listItemType = hibernateDAOFactory.getItemTypeMasterDAO().findAllByStatus(true);
        if (listItemType.size() > 0) {

            for (ItemTypeMaster departmentMaster : listItemType) {
                ComboboxRecInfo<ItemTypeMaster> combobox = new ComboboxRecInfo<>();
                combobox.setName(departmentMaster.getItemTypeName());
                combobox.setKeyData(departmentMaster);
                cbItemType.addItem(combobox);
            }
        }
    }

    public final void listenerTableModel() {
        modelTable.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() == TableModelEvent.DELETE) {
                    JOptionPane.showMessageDialog(null, "Delete Success!");
                }
                if (e.getType() == TableModelEvent.INSERT) {
                    JOptionPane.showMessageDialog(null, "Add new Item Success!");
                }
                if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 4) {
                    JOptionPane.showMessageDialog(null, "Update Item Success!");
                }
            }
        });
    }

    public final void listSelectionListener() {
        tableItem.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int rowSelected = tableItem.getSelectedRow();
                showDetail(getObject(rowSelected));
                btsave.setText("Update");
                btcancel.setEnabled(true);
            }
        });
    }

    @Override
    public void setObject(ItemMaster object) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    private void validSaveOrUpdateItemType(ItemMaster itemMaster) {
        if (validObject(itemMaster)) {
            ItemMaster itemMasterResult = hibernateDAOFactory.getItemMasterDAO().makePersistent(itemMaster);
            showDetail(itemMasterResult);
            if (btsave.getText().equals("Save")) {
                addRow(itemMaster, true);
            } else {
                updateRow(itemMaster, tableItem.getSelectedRow());
            }
        }
    }
}
